<?php

declare(strict_types=1);

namespace app\common\service\hrm;

use app\common\traits\ServiceTrait;
use app\common\dao\hrm\CompanyDao;
use app\common\traits\TreeServiceTrait;

/**
 * 单位 -- 业务
 * @author:kaige
 * @update:2022-06-17
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class CompanyService
{
  protected $dao = null;

  public function __construct()
  {
    $this->dao = new CompanyDao();
  }
  use ServiceTrait, TreeServiceTrait;

  /**
   * 重写 表格过滤条件
   * @param $post
   * @return array
   */
  public function _list_where($post)
  {
    $where = [];
    if (isset($post['status']) && $post['status'] != "") {
      $where[] = ['status', '=', $post['status']];
    }
    if (isset($post['keywords']) && !empty($post['keywords'])) {
      $where[] = ['name|fullname', 'like', '%' . $post['keywords'] . '%'];
    }
    $result['where'] = $where;
    $result['field'] = ["*,pid as parentId"];
    $result['order'] = ['sort' => 'asc', 'id' => 'desc'];
    return $result;
  }
  /**
   * 重写 根据查询结果，格式化数据
   * @param $list
   * @return mixed
   */
  public function _list_format($list)
  {
    foreach ($list as $k => $v) {
      if (isset($v['logo'])) {
        $list[$k]['logo'] = _img($v['logo']);
      }
      if (isset($v['pid'])) {
        $list[$k]['pobj'] = $this->getPid($v['pid']);
      }
    }
    return $list;
  }

  /**
   * 根据Id获取单位名称
   */
  public static function getNameById($id)
  {
    return (new CompanyDao())->getNameById($id);
  }

  /**
   * 获取单位列表
   * @return array
   */
  public static function getCompanyList()
  {
    return (new CompanyDao())->getListAll(['status' => 1], ['sort' => 'asc']);
  }

  /**
   * 获取所有列表树型
   * @return array
   */
  public function getCompanyTree()
  {
    $data = $this->dao->getListAll(true, ['sort' => 'asc']);
    return $this->createTree($data, 0);
  }

  /**
   * 把数组构建成一维的有缩进的树
   * @param $list
   * @param int $pid
   * @return array
   */
  public function createTree($list, $pid = 0, $level = 1)
  {
    $data = [];
    $str = "";
    for ($i = 0; $i < $level; $i++) {
      if ($i > 0) $str .= ' ';
    }
    if ($level == 1) {
      $str .= '';
    } else {
      $str .= ' ';
    }
    foreach ($list as $k => $v) {
      if ($v["pid"] == $pid) {
        $v['name'] = $str . $v['name'];
        $data[] = $v;
        $ch = $this->createTree($list, $v['id'], $level + 1);
        $data = array_merge($data, $ch);
      }
    }
    return $data;
  }

  /**
   * 获取所有单位数组-(id,pid,name,sort)
   * @return array
   */
  public function getCompanyArray()
  {
    $data = $this->dao->getListAll(true, ['sort' => 'asc'], ['id,pid,name,sort']);
    return $data;
  }

  /**
   * 获取单位数组，加入all元素
   * @return array
   */
  public function getCompanyArray2()
  {
    $all = ['id' => 'all', 'name' => '全部', 'pid' => 0, 'sort' => 0];
    $data  = $this->getCompanyArray();
    array_unshift($data, $all);
    return $data;
  }

  /**
   * 获取父单位
   * @param pid
   * @return object
   */
  public function getPid($pid)
  {
    $parentinfo = $this->dao->getInfoById($pid);
    return $parentinfo;
  }

  /**
   * 递归取得所有的父节点
   */
  public function getPids($id)
  {
    $data = [];
    $info = $this->dao->getInfoById($id);
    if (!$info) {
      return $data;
    }
    $info = object_array($info);
    //判断是否还有父节点，如果有，就取父节点，如果没有，就返回了
    if ($info['pid'] != 0) {
      $data = $this->getPids($info['pid']); //返回空数组或者二维数组
    }
    array_push($data, $info);
    return $data;
  }

  /**
   * 腾讯地图获取用户现在位置，定位于哪家公司，取出 省 市 县 街道
   */
  public function getlocation($data)
  {
    $return = ['data' => '', 'status' => false, 'msg' => "获取失败"];
    //取腾讯地图key
    $key = _conf('qq_map_key');
    $url = 'https://apis.map.qq.com/ws/geocoder/v1/?location=' . $data['lat'] . ',' . $data['lon'] . '&key=' . $key . '&get_poi=1';
    $result = $this->httpGet($url);
    if (empty($result)) {
      return $return;
    }
    $result = object_array($result);
    if ($result['status'] == 0) {
      $return['data'] = $result['result']['address_component']; //取地址部件
      $return['status'] = true;
    }
    return $return;
  }

  /**
   * 获取远程数据
   */
  protected function httpGet($url)
  {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
  }

  /**
   * 腾讯地图坐标转换
   */
  public function getqqlatlng($data)
  {
    $return = ['data' => '', 'status' => false, 'msg' => "获取失败"];
    //取腾讯地图key
    $key = _conf('qq_map_key');
    //可批量，以';'分开 lat,lng;lat,lng...这里只用单个坐标转换
    $url = 'https://apis.map.qq.com/ws/coord/v1/translate?locations=' . $data['lat'] . ',' . $data['lon'] . '&type=1&key=' . $key . '';
    $result = $this->httpGet($url);
    if (empty($result)) {
      return $return;
    }
    $result = object_array($result);
    if ($result['status'] == 0) {
      $return['data'] = $result['locations']; //取第一组
      $return['status'] = true;
    }
    return $return;
  }

  /**
   * 重写 保存表单数据
   * @param $data
   * @return array
   */
  public function saveForm($data)
  {
    if (empty($data)) {
      return _err(1002);
    }
    if (isset($data['id']) && !empty($data['id'])) {
      $compinfo = $this->dao->getInfoById($data['id']);
      if ($compinfo) {
        $result = $this->dao->update($data['id'], $data);
        if ($result) {
          if (isset($data['logo']) && !empty($data['logo'])) {
            _use_file($compinfo['logo'], -1); //旧图扣掉次数
            _use_file($data['logo'], 1); //新图加次数
          }
          if (isset($data['bl_sfz_img']) && !empty($data['bl_sfz_img'])) {
            _use_file($compinfo['bl_sfz_img'], -1); //旧图扣掉次数
            _use_file($data['bl_sfz_img'], 1); //新图加次数
          }
          if (isset($data['bl_img']) && !empty($data['bl_img'])) {
            _use_file($compinfo['bl_img'], -1); //旧图扣掉次数
            _use_file($data['bl_img'], 1); //新图加次数
          }
          // if (isset($data['bl_xkz_img']) && !empty($data['bl_xkz_img'])) {
          //   _use_file($compinfo['bl_xkz_img'], -1); //旧图扣掉次数
          //   _use_file($data['bl_xkz_img'], 1); //新图加次数
          // }
          return _ok(1021);
        }
      }
      return _err(1022);
    } else {
      $result = $this->dao->add($data);
      if ($result) {
        if (isset($data['logo']) && !empty($data['logo'])) {
          _use_file($data['logo'], 1); //新图加次数
        }
        if (isset($data['bl_sfz_img']) && !empty($data['bl_sfz_img'])) {
          _use_file($data['bl_sfz_img'], 1); //新图加次数
        }
        if (isset($data['bl_img']) && !empty($data['bl_img'])) {
          _use_file($data['bl_img'], 1); //新图加次数
        }
        // if (isset($data['bl_xkz_img']) && !empty($data['bl_xkz_img'])) {
        //   _use_file($data['bl_xkz_img'], 1); //新图加次数
        // }
        $return =  _ok(1023);
        if (!empty($result->id)) {
          $return['data'] = $result->id;
        }
        return $return;
      }
    }
    return _err(1005);
  }

  /**
   * 获取树型
   */
  public function companyTree()
  {
    $tree = [];
    $list = $this->dao->getListAll(
      ['status' => 1],
      ['sort' => 'asc'],
      ['name,id as value,id,pid']
    );
    if ($list) {
      $tree = \app\common\util\TreeUtil::list_to_tree($list, 0, 'id', 'pid', 'children');
    }
    return $tree;
  }
}
